<template>
    <div class="create_service">
        <div class="text_title mb20 ml10">{{ t('home.addService') }}</div>
        <ElForm
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
            label-position="right"
        >
            <ElFormItem :label="t('serviceManagement.serviceName')" prop="serviceName">
                <ElInput
                    v-model="ruleForm.serviceName"
                    class="w600"
                    :placeholder="t('serviceManagement.svcNamePlaceholder')"
                ></ElInput>
            </ElFormItem>
            <ElFormItem :label="t('serviceManagement.serviceDescription')" prop="serviceDesc">
                <ElInput
                    v-model="ruleForm.serviceDesc"
                    type="textarea"
                    :placeholder="t('serviceManagement.svcDescPlaceholder')"
                    class="w600"
                    :autosize="{ minRows: 4 }"
                ></ElInput>
            </ElFormItem>
            <ElFormItem :label="t('serviceManagement.priceDisplay')" prop="displayPrice">
                <ElInput
                    v-model.number="ruleForm.displayPrice"
                    :placeholder="t('serviceManagement.pricePlaceholder')"
                    class="w600"
                ></ElInput>
            </ElFormItem>
            <ElFormItem :label="t('serviceManagement.uploadImage')" prop="uploadImage">
                <ElUpload
                    :http-request="customUpload"
                    class="w600"
                    list-type="picture-card"
                    :limit="1"
                    v-model:file-list="fileList"
                    :class="{ limited: fileList?.length }"
                    accept="image/png,image/jpeg"
                >
                    <ElIcon><Plus /></ElIcon>
                </ElUpload>
            </ElFormItem>
        </ElForm>
        <div class="ml500">
            <ElButton
                v-logAction="{
                    page: router.currentRoute.value.path,
                    item: 'cancelCreate',
                    descriptions: '用户点击取消按钮',
                }"
                class="w80 but_cancel"
                @click="goBack"
            >
                {{ t('common.cancel') }}
            </ElButton>
            <ElButton
                v-logAction="{
                    page: router.currentRoute.value.path,
                    item: 'createService',
                    descriptions: '用户点击确定按钮',
                }"
                class="w80 but_confirms"
                @click="onSubmit(ruleFormRef)"
            >
                {{ t('common.confirm') }}
            </ElButton>
        </div>
        <div class="mt30 dashed_line"></div>
        <div v-if="route.query.editsID">
            <div class="mt30">
                <ElButton
                    v-logAction="{
                        page: router.currentRoute.value.path,
                        item: 'newSpecification',
                        descriptions: '用户点击新建规格按钮',
                    }"
                    class="but_create"
                    @click="showCreate"
                >
                    {{ t('serviceManagement.addSpec') }}
                </ElButton>
            </div>
            <ElTable v-if="specs && specs.length > 0" :data="specs" class="w_100">
                <ElTableColumn prop="name" :label="t('serviceManagement.specName')" width="180" />
                <ElTableColumn prop="options" :label="t('serviceManagement.specTypes')">
                    <template #default="scope">
                        <div>
                            <span v-for="(data, index) in scope.row.options" :key="index" class="mr5">
                                <el-tag class="mx-1">{{ data.optionName }}</el-tag>
                            </span>
                        </div>
                    </template>
                </ElTableColumn>
                <ElTableColumn :label="t('serviceManagement.operation')">
                    <template #default="scope">
                        <ElButton
                            v-logAction="{
                                page: router.currentRoute.value.path,
                                item: 'deleteSpecification',
                                descriptions: '用户点击删除规格按钮',
                            }"
                            type="text"
                            @click="deleteSpec(scope.row)"
                        >
                            {{ t('common.delete') }}
                        </ElButton>
                    </template>
                </ElTableColumn>
            </ElTable>
            <div class="mt30">
                <ElButton
                    v-logAction="{
                        page: router.currentRoute.value.path,
                        item: 'addPrice',
                        descriptions: '用户点击添加价格按钮',
                    }"
                    class="but_create"
                    @click="showSkusCreate"
                >
                    {{ t('serviceManagement.addSku') }}
                </ElButton>
            </div>
            <ElTable v-if="skus && skus.length > 0" :data="skus" class="w_100">
                <template v-for="item in specs" :key="item.name">
                    <ElTableColumn :prop="item.name" :label="item.name" width="180" />
                </template>
                <ElTableColumn prop="price" :label="t('serviceManagement.priceWithUnit')">
                    <template #default="scope">
                        <span>{{ scope.row.price }}</span>
                    </template>
                </ElTableColumn>
                <ElTableColumn :label="t('serviceManagement.operation')">
                    <template #default="scope">
                        <ElButton
                            v-logAction="{
                                page: router.currentRoute.value.path,
                                item: 'modifyPrice',
                                descriptions: '用户点击编辑价格按钮',
                            }"
                            type="text"
                            @click="editSpec(scope.row)"
                        >
                            {{ t('common.edit') }}
                        </ElButton>
                        <ElButton
                            v-logAction="{
                                page: router.currentRoute.value.path,
                                item: 'deletePrice',
                                descriptions: '用户点击删除价格按钮',
                            }"
                            type="text"
                            @click="deleteSku(scope.row)"
                        >
                            {{ t('common.delete') }}
                        </ElButton>
                    </template>
                </ElTableColumn>
            </ElTable>
        </div>
        <ElDialog v-model="createSpecificationsVisible" :title="t('serviceManagement.addSpec')" width="30%">
            <ElForm :label-width="'100px'">
                <ElFormItem :label="`${t('serviceManagement.specName')}：`">
                    <ElInput
                        v-model="attributeName"
                        class="input-control"
                        :placeholder="t('serviceManagement.specNamePlaceholder')"
                    ></ElInput>
                </ElFormItem>
                <ElFormItem :label="`${t('serviceManagement.specTypes')}：`">
                    <div v-for="(item, index) in attributeValue" :key="item.key">
                        <ElInput v-model="item.value" class="input-control"></ElInput>
                        <ElButton
                            v-if="index === 0"
                            v-logAction="{
                                actionId: 'click',
                                actionPage: '/home/service-management/modify',
                                item: '新增按钮',
                                paras: '添加规格弹窗用户点击新增按钮',
                            }"
                            class="ml20"
                            type="text"
                            @click="addEl"
                        >
                            {{ t('common.add') }}
                        </ElButton>
                        <ElButton v-if="attributeValue.length > 1" class="ml20" type="text" @click="del(item.key)">
                            {{ t('common.delete') }}
                        </ElButton>
                    </div>
                </ElFormItem>
            </ElForm>
            <template #footer>
                <span class="dialog-footer">
                    <ElButton class="but_cancel" @click="cancelCreate">{{ t('common.cancel') }}</ElButton>
                    <ElButton
                        v-logAction="{
                            actionId: 'click',
                            actionPage: '/home/service-management/modify',
                            item: '确定按钮',
                            paras: '添加规格弹窗用户点击确定按钮',
                        }"
                        class="but_confirms"
                        @click="createSpecifications"
                    >
                        {{ t('common.confirm') }}
                    </ElButton>
                </span>
            </template>
        </ElDialog>
        <ElDialog v-model="createSkusVisible" :title="t('serviceManagement.skuConfig')" width="30%">
            <ElForm :label-width="'100px'">
                <ElFormItem v-for="option in serviceOptionList" :key="option.name" :label="option.name + ':'">
                    <el-select
                        v-model="option.value"
                        class="input-control"
                        :placeholder="t('serviceManagement.pleaseSelect')"
                    >
                        <ElOption
                            v-for="item in option.options"
                            :key="item.optionId"
                            :label="item.optionName"
                            :value="item.optionId"
                        ></ElOption>
                    </el-select>
                </ElFormItem>
                <ElFormItem :label="`${t('serviceManagement.price')}：`">
                    <ElInput
                        v-model="ruleForm.price"
                        class="input-control"
                        :placeholder="t('serviceManagement.inputPricePlaceholder')"
                    ></ElInput>
                </ElFormItem>
            </ElForm>
            <template #footer>
                <span class="dialog-footer">
                    <ElButton
                        v-logAction="{
                            page: router.currentRoute.value.path,
                            item: 'unconfirmRevisionPrice',
                            descriptions: '用户点击取消价格配置按钮',
                        }"
                        class="but_cancel"
                        @click="cancelCreate"
                    >
                        {{ t('common.cancel') }}
                    </ElButton>
                    <ElButton
                        v-logAction="{
                            page: router.currentRoute.value.path,
                            item: 'confirmRevisionPrice',
                            descriptions: '用户点击确定价格配置按钮',
                        }"
                        class="but_confirms"
                        @click="createSkus"
                    >
                        {{ t('common.confirm') }}
                    </ElButton>
                </span>
            </template>
        </ElDialog>
    </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router';
import { ref, reactive, Ref } from 'vue';
import { ElMessage, UploadUserFile } from 'element-plus';
import type { FormInstance } from 'element-plus';
import {
    getServiceById,
    createService,
    deleteSpecification,
    createServiceSpecification,
    createServiceSelection,
    deleteServiceSkuBySkuId,
    updateServiceSelection,
    updateService,
} from '@/api/api.query.util';
import { t, onLocaleChanged } from '@/i18n';
import { Plus } from '@element-plus/icons-vue';
import { UploadRequestOptions } from 'element-plus';
import { getImage, uploadImage } from '@/api/api.upload';

const createSpecificationsVisible = ref(false);
const createSkusVisible = ref(false);
const router = useRouter();
const route = useRoute();
const ruleForm = reactive({
    serviceName: '',
    serviceDesc: '',
    displayPrice: '',
    price: '',
    editSkuId: '',
    imgSrc: '',
});

const fileList = ref<UploadUserFile[]>();

const rules = ref(getRules());
function getRules() {
    return {
        serviceName: [
            {
                required: true,
                message: t('serviceManagement.svcNameEmptyTip'),
                trigger: 'blur',
            },
        ],
        displayPrice: [
            {
                required: true,
                message: t('serviceManagement.dspPriceEmptyTip'),
                trigger: 'blur',
            },
            {
                type: 'number',
                message: t('serviceManagement.priceMustBeNum'),
            },
        ],
    };
}
onLocaleChanged(() => {
    rules.value = getRules();
});

const specs: Ref<
    Array<{
        name: string;
        options: any;
    }>
> = ref([]);
const skus = ref([]);
const attributeName = ref('');
const attributeValue = ref([
    {
        key: new Date().getTime(),
        value: '',
    },
]);
const serviceOptionList = ref([]);
if (route.query.editsID) {
    getServiceDetails();
}

function getServiceDetails() {
    getServiceById({
        method: 'post',
        data: {
            serviceId: route.query.editsID,
        },
    }).then((res) => {
        specs.value = res.result.specs || [];
        if (specs.value.length > 0) {
            serviceOptionList.value = specs.value.map((item) => ({
                name: item.name,
                value: '',
                selectionId: '',
                options: item.options,
            }));
        }
        if (res.result.skus) {
            res.result.skus.forEach((item) => {
                item.selections.forEach((a) => {
                    item[a.specName] = a.optionName;
                });
            });
        }
        skus.value = res.result.skus;
        ruleForm.serviceName = res.result.serviceName;
        ruleForm.serviceDesc = res.result.serviceDesc;
        ruleForm.displayPrice = res.result.displayPrice;
        ruleForm.imgSrc = res.result.imgSrc;

        if (ruleForm.imgSrc) {
            fileList.value = [{ response: ruleForm.imgSrc, name: ruleForm.imgSrc }];
            getImage(ruleForm.imgSrc).then((res) => {
                if (res.data.type !== 'application/json') {
                    fileList.value = [
                        { response: ruleForm.imgSrc, name: ruleForm.imgSrc, url: URL.createObjectURL(res.data) },
                    ];
                }
            });
        }
    });
}
function deleteSpec(row: any) {
    deleteSpecification({
        method: 'delete',
        data: {
            specId: row.specId,
        },
    }).then((res) => {
        ElMessage.success(t('serviceManagement.deleteSuccessful'));
        getServiceDetails();
    });
}
function deleteSku(row: any) {
    deleteServiceSkuBySkuId({
        method: 'delete',
        data: {
            skuId: row.skuId,
        },
    }).then((res) => {
        ElMessage.success(t('serviceManagement.deleteSuccessful'));
        getServiceDetails();
    });
}
function goBack() {
    router.push({ name: '/home/service-management' });
}
const ruleFormRef = ref<FormInstance>();
const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
        if (valid) {
            ruleForm.imgSrc = (fileList.value?.[0].response as string) || '';
            if (route.query.editsID) {
                updateService({
                    method: 'post',
                    data: { ...ruleForm, ...{ serviceId: route.query.editsID } },
                }).then((res) => {
                    ElMessage.success(t('serviceManagement.modifiedSuccessfully'));
                    goBack();
                });
            } else {
                createService({
                    method: 'post',
                    data: ruleForm,
                }).then((res) => {
                    ElMessage.success(t('serviceManagement.addSuccessfully'));
                    goBack();
                });
            }
        }
    });
};
function cancelCreate() {
    createSpecificationsVisible.value = false;
    createSkusVisible.value = false;
}
function showCreate() {
    attributeName.value = '';
    attributeValue.value = [
        {
            key: new Date().getTime(),
            value: '',
        },
    ];
    createSpecificationsVisible.value = true;
}
function createSkus() {
    if (ruleForm.editSkuId) {
        updateServiceSelection({
            method: 'post',
            data: {
                skuId: ruleForm.editSkuId,
                price: ruleForm.price,
                optionProperties: serviceOptionList.value.map((item) => ({
                    optionId: item.value,
                    selectionId: item.selectionId,
                })),
            },
        }).then((res) => {
            ElMessage.success(t('serviceManagement.modifiedSuccessfully'));
            getServiceDetails();
        });
        ruleForm.editSkuId = '';
    } else {
        createServiceSelection({
            method: 'post',
            data: {
                serviceId: route.query.editsID,
                price: ruleForm.price,
                optionIds: serviceOptionList.value.map((item) => item.value),
            },
        }).then((res) => {
            ElMessage.success(t('serviceManagement.addSuccessfully'));
            getServiceDetails();
        });
    }
    ruleForm.price = '';
    createSkusVisible.value = false;
}
function createSpecifications() {
    const valueArr = attributeValue.value.map((item: any) => item.value).filter((s) => s && s.trim());
    if (!attributeName.value) {
        ElMessage.warning(t('serviceManagement.specNameEmptyTip'));
        return;
    }
    if (valueArr.length === 0) {
        ElMessage.warning(t('serviceManagement.specTypeEmptyTip'));
        return;
    }
    if (new Set(valueArr).size !== valueArr.length) {
        ElMessage.warning(t('serviceManagement.specTypeDuplicateTip'));
        return;
    }
    createServiceSpecification({
        method: 'post',
        data: {
            serviceId: route.query.editsID,
            name: attributeName.value,
            serviceOptionList: valueArr,
        },
    }).then((res) => {
        ElMessage.success(t('serviceManagement.addSuccessfully'));
        getServiceDetails();
    });
    createSpecificationsVisible.value = false;
    attributeName.value = '';
    attributeValue.value = [
        {
            key: new Date().getTime(),
            value: '',
        },
    ];
}
function addEl() {
    attributeValue.value.push({
        key: new Date().getTime(),
        value: '',
    });
}
function del(key: any) {
    attributeValue.value.forEach(
        (
            item: {
                key: any;
            },
            index: number,
        ) => {
            if (item.key === key) {
                attributeValue.value.splice(index, 1);
            }
        },
    );
}
function showSkusCreate() {
    createSkusVisible.value = true;
}
function editSpec(row: any) {
    createSkusVisible.value = true;
    ruleForm.editSkuId = row.skuId;
    ruleForm.price = row.price;
    serviceOptionList.value.forEach((item) => {
        const option = row.selections.find((a) => a.optionName === row[item.name]);
        item.value = option.optionId;
        item.selectionId = option.selectionId;
    });
}

/**
 *
 */
function customUpload(options: UploadRequestOptions) {
    return uploadImage(options.file).then((res) => res.data.result);
}
</script>

<style scoped>
.create_service {
    padding: 25px 30px 20px 20px;
    background-color: var(--bg-default);
}
.text_title {
    font-size: var(--font-size);
    color: var(--text-primary);
}
.but_confirms {
    background-color: var(--btn_default);
    border-radius: 4px;
    color: var(--text-default);
}

.dashed_line {
    border-top: 1px dashed #dfe1e6;
}
.input-control {
    color: #666666;
    width: 100%;
    max-width: 300px;
}
.but_cancel {
    border-radius: 4px;
    color: var(--text-secondary);
}

.upload-btn {
    border-radius: 4px;
    background-color: var(--btn_primary);
    border-color: var(--btn_primary);
    color: var(--text-default);
    min-height: 32px;
    padding: 0 20px;
}

.limited:deep(.el-upload--picture-card) {
    display: none;
}

:deep(.el-upload-list__item-thumbnail) {
    object-fit: cover;
}
</style>
